package com.pengshun.modules.api.order.service.impl;

import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.mapper.OrderAllotTransportMapper;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.mapper.TransportMapper;
import com.pengshun.modules.api.order.repository.MerchantOrderRepository;
import com.pengshun.modules.api.order.repository.OrderAllotTransportRepository;
import com.pengshun.modules.api.order.service.OrderAllotService;
import com.pengshun.modules.api.order.service.dto.OrderAllotTransportDto;
import com.pengshun.modules.api.order.service.mapstruct.OrderAllotTransportTodo;
import com.pengshun.modules.api.transport.dto.TransportOrderDto;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.common.OperationType;
import com.pengshun.modules.common.OrderCommon;
import com.pengshun.modules.common.PagePara;
import com.pengshun.modules.domain.Merchant;
import com.pengshun.modules.domain.MerchantOrder;
import com.pengshun.modules.domain.OperateRecord;
import com.pengshun.modules.domain.OrderAllotTransport;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author luoligang
 * @create 2021/2/23
 */
@Service
@RequiredArgsConstructor
public class OrderAllotServiceImpl implements OrderAllotService {

    private final TransportMapper transportMapper;
    private final OrderAllotTransportRepository orderAllotTransportRepository;
    private final OrderAllotTransportTodo orderAllotTransportTodo;
    private final SystemMapper systemMapper;
    private final MerchantOrderRepository merchantOrderRepository;
    private final OrderAllotTransportMapper orderAllotTransportMapper;
    private final MerchantRepository merchantRepository;
    private  final MessageSource messageSource;

    @Override
    public BaseResult allotOrderList(OrderAllotTransportDto para) {
        List<OrderAllotTransportDto> list=orderAllotTransportMapper.findListByOrderIdAndStatus(para.getOrderId(),para.getStatus());
        return new BaseResult(0,list);
    }

    @Override
    public BaseResult save(OrderAllotTransportDto para) {
        //判断订单剩余煤炭数量
        MerchantOrder order=merchantOrderRepository.findById(para.getOrderId()).orElseGet(MerchantOrder::new);
        //判断订单状态
        if(order.getOrderStatus()!=6){
            return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.update.status", null, Locale.CHINA));
        }
        //分配运费不能大于订单运费
        if(para.getFreight().compareTo(order.getFreight())== 1){
            return new BaseResult(1, messageSource.getMessage("OrderAllotServiceImpl.save.freight.big", null, Locale.CHINA));
        }
        //订单总煤炭数量
        BigDecimal oldNUm=order.getNumber();
        //查询分配过的 待确认 已确认 已发布的总数量
        BigDecimal allotNum=orderAllotTransportMapper.findAllotCoalSumNum(para.getOrderId());
        allotNum=allotNum==null?new BigDecimal(0):allotNum;

        //总数量减分配过的 减去需要分配的  大于0
        BigDecimal lastNum=oldNUm.subtract(allotNum).subtract(new BigDecimal(para.getAllotNumber()));
        if(lastNum.compareTo(BigDecimal.ZERO)==-1){
            //说明剩余数量不足
            return new BaseResult(1, messageSource.getMessage("OrderAllotServiceImpl.save.compareTo", null, Locale.CHINA));
        }
        //判前后台总运费是否一致
        BigDecimal totalFreight=para.getFreight().multiply(new BigDecimal(para.getAllotNumber()));
        if(totalFreight.compareTo( para.getTotalFreight())!=0){
            return new BaseResult(1, messageSource.getMessage("OrderAllotServiceImpl.save.lastNum", null, Locale.CHINA));
        }
        para.setStatus(OrderCommon.ALLOT_STATEUS_ONE);
        para.setAllotTime(new Date());
        para.setOrderNo(order.getOrderNo());
        para.setIsApply(0);
        orderAllotTransportRepository.save(orderAllotTransportTodo.toEntity(para));
        return new BaseResult(0,messageSource.getMessage("OrderAllotServiceImpl.save.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult update(OrderAllotTransportDto para) {
        OrderAllotTransport transport=orderAllotTransportRepository.findById(para.getOrderAllotTransportId()).orElseGet(OrderAllotTransport::new);
        //判断订单剩余煤炭数量
        MerchantOrder order=merchantOrderRepository.findById(transport.getOrderId()).orElseGet(MerchantOrder::new);
        //分配运费不能大于订单运费
        if(para.getFreight().compareTo(order.getFreight())== 1){
            return new BaseResult(1, messageSource.getMessage("OrderAllotServiceImpl.save.freight.big", null, Locale.CHINA));
        }
        //订单总煤炭数量
        BigDecimal oldNUm=order.getNumber();
        //查询分配过的 待确认 已确认 已发布的总数量
        BigDecimal allotNum=orderAllotTransportMapper.findAllotCoalSumNum(para.getOrderId());
        allotNum=allotNum==null?new BigDecimal(0):allotNum;
        //之前分配的数量

        BigDecimal beforeNum=new BigDecimal(transport.getAllotNumber());
        //总数量减分配过的 减去需要分配的 +之前分配的  大于0
        BigDecimal lastNum=oldNUm.subtract(allotNum).subtract(new BigDecimal(para.getAllotNumber())).add(beforeNum);
        if(lastNum.compareTo(BigDecimal.ZERO)==-1){
            //说明剩余数量不足
            return new BaseResult(1,messageSource.getMessage("OrderAllotServiceImpl.update.BigDecimal", null, Locale.CHINA));
        }
        //判前后台总运费是否一致
        BigDecimal totalFreight=para.getFreight().multiply(new BigDecimal(para.getAllotNumber()));
        if(totalFreight.compareTo( para.getTotalFreight())!=0){
            return new BaseResult(1,messageSource.getMessage("OrderAllotServiceImpl.update.lastNum", null, Locale.CHINA));
        }
        transport.setAllotNumber(para.getAllotNumber());
        transport.setFreight(para.getFreight());
        transport.setTotalFreight(para.getTotalFreight());
        orderAllotTransportRepository.save(transport);
        return new BaseResult(0,messageSource.getMessage("OrderAllotServiceImpl.update.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult delete(Long orderAllotTransportId) {
        orderAllotTransportRepository.deleteById(orderAllotTransportId);
        return new BaseResult(0);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateOrderAllotTransport(TransportOrderDto para) throws Exception {
        OrderAllotTransport transport=orderAllotTransportRepository.findById(para.getOrderAllotTransportId()).orElseGet(OrderAllotTransport::new);
        transport.setStatus(para.getStatus());
        transport.setRemark(para.getRemark());
        String message="";
        if(para.getStatus()==4){
            //设定拒绝时间
            transport.setBackTime(new Date());
            message=messageSource.getMessage("OrderAllotServiceImpl.updateOrderAllotTransport.back", null, Locale.CHINA);
        }
        if(para.getStatus()==2){
            //设定确定时间
            transport.setSureTime(new Date());
            message=messageSource.getMessage("OrderAllotServiceImpl.updateOrderAllotTransport.sure", null, Locale.CHINA);
        }
        orderAllotTransportRepository.save(transport);
        //操作表插入数据
        OperateRecord operateRecord = new OperateRecord(para.getRemark(), para.getOrderAllotTransportId(), OperationType.ONE_STATUS, para.getUserId());
        systemMapper.insertOperateRecord(operateRecord.getContent(), operateRecord.getId(), operateRecord.getId(), operateRecord.getUserId());
        return new BaseResult(0,message);

    }

    @Override
    public BaseResult getOrderDetil(Long orderAllotTransportId) {
        TransportOrderDto dto = transportMapper.getOrderDetil(orderAllotTransportId);
        dto.setEndAddress(dto.getProvince()+dto.getCity()+dto.getDistrict()+dto.getEndAddress());
        return new BaseResult(0, dto);
    }


    @Override
    public BaseResult getOrderListByStatus(PagePara dto) {
        int page = (dto.getPage()) * dto.getSize();
        Merchant merchant=merchantRepository.findByUserId(dto.getUserId());
        List<TransportOrderDto> list = transportMapper.getOrderListByStatus(page < 0 ? 0 : page, dto.getSize(), dto.getStatus(),merchant.getId());
        return new BaseResult(0, list);
    }

}
